package com.cskaoyan._04hashcode;

/**
 * @description:
 * @author: 景天
 * @date: 2023/2/14 16:43
 **/

public class Demo2 {
    public static void main(String[] args) {
        Teacher t1 = new Teacher("zs", new Subject("数学"));
        Teacher t2 = new Teacher("zs", new Subject("数学"));
        System.out.println("t1.equals(t2) = " + t1.equals(t2));
        System.out.println(t1.hashCode());
        System.out.println(t2.hashCode());
    }
}

class Teacher{
    String name;
    Subject subject;

    public Teacher(String name, Subject subject) {
        this.name = name;
        this.subject = subject;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Teacher teacher = (Teacher) o;

        if (name != null ? !name.equals(teacher.name) : teacher.name != null) return false;
        return subject != null ? subject.equals(teacher.subject) : teacher.subject == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (subject != null ? subject.hashCode() : 0);
        return result;
    }
}

class Subject{
    String subjectName;

    public Subject(String subjectName) {
        this.subjectName = subjectName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Subject subject = (Subject) o;

        return subjectName != null ? subjectName.equals(subject.subjectName) : subject.subjectName == null;
    }

    // 这个类也要重写hashcode方法
    @Override
    public int hashCode() {
        return subjectName != null ? subjectName.hashCode() : 0;
    }
}